package com.wuxl.prada;

/**
 * Description:
 *
 * @author 诸葛小猿
 * @date 2024-12-19
 */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

public class VideoClipper {
    public static void clipVideo(String ffmpeg, String inputVideo, String outputDir, List<WordExtractor.WordTimestamp> wordTimestamps) throws IOException, InterruptedException {
        int i = 0;
        for (WordExtractor.WordTimestamp wordTimestamp : wordTimestamps) {
            i++;
            String word = wordTimestamp.getWord();
            String startTime = wordTimestamp.getStartTime();
            String endTime = wordTimestamp.getEndTime();
            String outputFilePath = outputDir + "/" + word + "_" + i + ".mkv";

            // FFmpeg command to clip the video and add subtitles
//            String command = ffmpeg + " -i " + inputVideo + " -ss " + startTime + " -to " + endTime + " -vf \"subtitles=subtitles.srt:force_style='FontName=Arial,FontSize=24,PrimaryColour=&H0000FF&',drawtext=text='" + word + "':fontcolor=red:fontsize=24:box=1:boxcolor=yellow@0.5:boxborderw=5:x=(w-text_w)/2:y=(h-text_h)/2\" -c:a copy " + outputFilePath;
//            String command = ffmpeg + " -i " + inputVideo + " -ss " + startTime + " -to " + endTime + " -c:v copy -c:a copy " + outputFilePath + " -y";
            String command = String.format("%s -i %s -ss %s  -to %s -vcodec copy -acodec copy %s -y", ffmpeg, inputVideo,startTime, endTime, outputFilePath);

            System.out.println(command);

            Process process = Runtime.getRuntime().exec(command);

            // 读取标准输出
            BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
            BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));

            // 读取并打印标准输出
            System.out.println("Standard Output:");
            String s;
            while ((s = stdInput.readLine()) != null) {
                System.out.println(s);
            }

            // 读取并打印错误输出
            System.out.println("Standard Error:");
            while ((s = stdError.readLine()) != null) {
                System.out.println(s);
            }

            // 等待进程完成
            int exitCode = process.waitFor();
            System.out.println("Command exited with code: " + exitCode);


            // Print the output of the FFmpeg command
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        }
    }
}
